import Foundation

public extension Calendar {
    static let gregorian = Calendar(identifier: .gregorian)
    static let chinese = Calendar(identifier: .chinese)
    
    func generateDates(for date: Date) -> [Date] {
        var dates: [Date] = []
        guard let range = range(of: .day, in: .month, for: date) else {
            return dates
        }
        // Range(1..<?) to 0..<?
        let startOfMonth = date.startOfMonth
        for value in Array(range).indices {
            let date = self.date(byAdding: .day, value: value, to: startOfMonth) ?? startOfMonth
            dates.append(date)
        }
        
        var weekday = startOfMonth.weekday
        weekday += weekday >= firstWeekday ? 0 : 7

        let lastCount = weekday - firstWeekday

        if lastCount > 0 {
            var lastDates: [Date] = []
            for value in (1...lastCount).reversed() {
                let date = self.date(byAdding: .day, value: Int(-value), to: startOfMonth) ?? startOfMonth
                lastDates.append(date)
            }
            dates = lastDates + dates
        }

        let total = dates.count > 35 ? 42 : 35
        let nextCount = total - dates.count
        
        if nextCount > 0, let endOfMonth = dates.last {
            var nextDates: [Date] = []
            for value in 1...nextCount {
                let date = self.date(byAdding: .day, value: value, to: endOfMonth) ?? endOfMonth
                nextDates.append(date)
            }
            dates += nextDates
        }
        
        return dates
    }
    
    // 生成和传入日期相邻的7天日期，根据firstWeekday排序
    func generateWeekDates(for date: Date) -> [Date] {
        var resultDates = [Date]()
        // 获取输入日期是星期几
        let weekday = date.weekday
        let startWeek = firstWeekday
        var val = 0
        if startWeek > weekday {    // 起始星期日期大于当前日期
            val = 7 - (startWeek - weekday)
            if val > 0 {
                for value in (1...val).reversed() {
                    let date = self.date(byAdding: .day, value: Int(-value), to: date) ?? date
                    resultDates.append(date)
                }
            }
        } else {    // 起始星期日期小于等于当前日期
            val = weekday - startWeek
            if val > 0 {
                for value in (1...val).reversed() {
                    let date = self.date(byAdding: .day, value: Int(-value), to: date) ?? date
                    resultDates.append(date)
                }
            }
        }
        resultDates.append(date)
        val = 7 - resultDates.count
        if val > 0 {
            for value in 1...val {
                let date = self.date(byAdding: .day, value: value, to: date) ?? date
                resultDates.append(date)
            }
        }
        return resultDates
    }
}
